from bs4 import BeautifulSoup


def prettify_xpath_html(q):
    '''
    重新构造html结果
    'zh-CHS','ko'
    '''
    all_tags = {} # 全局记录标签 -  有序
    text_items = {}
    from lxml import etree
    html = etree.HTML(q)
    child_nodes = html.xpath('//*')
    # 遍历并打印子节点文本内容 - 并且按顺序记录
    for index, node in enumerate(child_nodes):
        name = node.xpath("name()")
        text = ''.join([t.strip() for t in node.xpath('./text()')])
        if not text:
            continue
        # print(text)
        node.text = text
        # # node.text += '111'
        text = node.text
        if (text is None or not text.strip()) and name != 'img':
            continue
        all_tags[str(index)] = name
        if name == 'img':
            all_tags[str(index)] = etree.tostring(node, encoding='utf-8').decode('utf-8')
        else:
            text_items[str(index)] = text
    old_text_list = list(text_items.values())
    for ti, t_index in enumerate(text_items.keys()):
        name = all_tags[t_index]
        __new_text = f'<{name}>{old_text_list[ti]}</{name}>'
        all_tags[t_index] = __new_text

    new_body = f'<div> {"".join(all_tags.values())} </div>'
    print(new_body)


def prettify_css_html(html):
    '''
    简化html源码 - 为了翻译后格式不乱
    '''
    soup = BeautifulSoup(html, 'html.parser')
    for tag in soup.find_all(string=True):
        if not tag.strip():
            continue
        print(tag.parent.name, tag.string)
    # print(soup.prettify())

if __name__ == '__main__':
    html_content = '''
        <html>
        <body>
        <div>
        Div 1.0 Text
        <p>Paragraph 1 Text</p >
        Div 1 Text
        <p>Paragraph 2 Text</p >
        </div>
        <div>
        <span>Span Text</span>
        Div 2 Text
        </div>
        <div>Div 3 Text
        <ul>
        <li>List Item 1</li>
        <li>List Item 2</li>
        </ul>
        </div>
        </body>
        </html>
    '''
    prettify_css_html(html_content)